package com.ec50n9.server.module.issueCategory

import com.ec50n9.server.common.mayBeAlreadyExist
import com.ec50n9.server.common.mayBeNotFound
import com.ec50n9.server.common.render
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Service
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import java.util.*

interface IssueCategoryRepository : CrudRepository<IssueCategory, String> {

    fun findByCode(code: String): Optional<IssueCategory>
}

@Service
class IssueCategoryService(private val issueCategoryRepository: IssueCategoryRepository) {

    private val name="问题分类"

    fun findOne(code: String): IssueCategory = mayBeNotFound(name) {
        issueCategoryRepository.findByCode(code).orElseThrow()
    }

    fun findAll(): Iterable<IssueCategory> = issueCategoryRepository.findAll()

    fun newOne(issueCategory: IssueCategory) = mayBeAlreadyExist(name){
        issueCategoryRepository.save(issueCategory)
    }

    fun update(issueCategory: IssueCategory) = issueCategoryRepository.save(issueCategory)

    fun delete(issueCategory: IssueCategory) = issueCategoryRepository.delete(issueCategory)
}

@Tag(name = "问题分类管理")
@RestController
@RequestMapping("/api/issue-categorys")
class IssueCategoryController(private val issueCategoryService: IssueCategoryService) {

    @Operation(summary = "获取全部")
    @GetMapping
    fun findAll(): List<IssueCategoryQueryRendered?> = issueCategoryService.findAll().render()

    @Operation(summary = "通过code获取")
    @GetMapping("/{code}")
    fun findOne(@PathVariable code: String): IssueCategoryQueryRendered? = issueCategoryService.findOne(code).render()

    @Operation(summary = "新建")
    @PostMapping
    fun newOne(@RequestBody @Validated createForm: IssueCategoryCreateForm): IssueCategoryQueryRendered? =
        with(issueCategoryService){
            val temp = IssueCategory("", "")
            createForm.render(temp)
            newOne(temp).render()
        }

    @Operation(summary = "更新")
    @PatchMapping("/{code}")
    fun update(
        @PathVariable code: String,
        @RequestBody updateForm: IssueCategoryUpdateForm
    ): IssueCategoryQueryRendered? =
        with(issueCategoryService) {
            val temp = findOne(code)
            updateForm.render(temp, true)
            update(temp).render()
        }

    @Operation(summary = "删除")
    @DeleteMapping("/{code}")
    fun delete(@PathVariable code: String) =
        with(issueCategoryService) {
            delete(findOne(code))
        }
}